<template>
	<div>
		<div class="publishFrom enclosure">
			<div class="publishFrom_ad buttonCSS">
				<el-button  size="primary" @click="addAttachments = true">添加附件</el-button>
				<el-button  size="primary" @click="deleteMuilt_confirm">删除所选</el-button>
			</div>
			<template>
				<el-table
				ref="multipleTable"
				:data="listData"
				tooltip-effect="dark"
				style="width: 100%"
				border
				v-loading="loading.status"
		  	  :element-loading-text="loading.txt"
				@selection-change="tableSelectionChange">
					<el-table-column
						type="selection"
						 align="center"
						width="40">
					</el-table-column>
					<el-table-column
						prop="name"
						label="附件名称"
						 align="center"
						width="120">
					</el-table-column>
					<el-table-column
						prop="postfix"
						label="附件类型"
						 align="center"
						width="80">
					</el-table-column>
					<el-table-column
						prop="create_time"
						width="150"
						label="上传时间"
						show-overflow-tooltip>
					</el-table-column>
					<el-table-column
						prop="comment"
						label="备注"
						 align="center"
						show-overflow-tooltip>
					</el-table-column>
					<el-table-column
					    label="操作"
					    align="center"
					    width="160">
					    <template slot-scope="scope">
					       <el-button @click="editFileBox(scope.row)" type="text" size="small">编辑</el-button>
					       <el-button @click="down(scope.row.path,scope.row.name)" type="text" size="small">下载</el-button>
					      <el-button @click="delete_confirm(scope.row)" type="text" size="small">删除</el-button>
					    </template>
					  </el-table-column>
				</el-table>
			</template>
			<div class="pageBox" v-if="total_number > listParam.page_size">
				<el-pagination
				    @size-change="handleSizeChange"
				    @current-change="handleCurrentChange"
				    :current-page="listParam.page_index"
				    :page-size="listParam.page_size"
				    layout="total,  prev, pager, next, jumper"
				    :total="total_number">
				</el-pagination>
			</div>
		</div>
		<!-- 添加附件 -->
		<el-dialog
			title="添加附件"
			:visible.sync="addAttachments"
			width="800px"
			custom-class="addAttachments"
			:before-close="resetForm"
			:close-on-click-modal="false">
			<div class="addAttachments-c">
				<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
					<el-form-item label="上传附件" prop="select_or_not" v-if="parseInt(ruleForm.id) === 0 ">
						 <uploader 
						 :options="uploadOptions" 
						 :autoStart="false" 
						 ref="uploader" 
						 :file-status-text="statusText" 
						 @file-added="fileAdd" 
						 @files-submitted="fileSubmit" 
						 @file-removed="fileRemoved" 
						 @file-success="fileSuccess" 
						 @file-error="fileFail"  
						 class="uploader-enclosure">
						    <uploader-unsupport></uploader-unsupport>
						    <uploader-btn :directory="false" :attrs="attrs" v-if="selectFileShow" :single="true">
						    	<span>选择文件</span></i>
						    </uploader-btn>
						    <uploader-list  v-if="selectFileShow===false?true:false"></uploader-list>
						 </uploader>
					</el-form-item>
					<el-form-item label="权限" prop="authority">
						<el-radio-group v-model="ruleForm.authority">
							<el-radio label="1">公开</el-radio>
							<el-radio label="0">不公开</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="附件名称" prop="name">
						<el-input v-model.trim="ruleForm.name" placeholder="请输入附件名称, 20个字符内" maxlength="20"></el-input>
						<el-input v-model.trim="ruleForm.name" placeholder="请输入附件名称, 20个字符内" maxlength="20" v-show='false'></el-input>
					</el-form-item>
					<el-form-item label="附件备注" prop="comment">
						<el-input type="textarea" v-model.trim="ruleForm.comment"
						:rows="5"
						resize="none"
						placeholder="请输入附件备注,不超过200个字符" maxlength="200"></el-input>
						<span class="numberWord"><i>{{ ruleForm.comment.length }}</i>/200</span>
					</el-form-item>
					<el-form-item class="sendNotice_btn buttonCSS">
						<el-button type="primary" plain @click="addAttachments = false">取消</el-button>
						<el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
					</el-form-item>
				</el-form>
			</div>
		</el-dialog>
		<!-- 编辑 -->
		<el-dialog
			title="编辑题干"
			:visible.sync="editorQuestion"
			width="800px"
			custom-class="editorQuestion"
			:close-on-click-modal="false">
			<div class="editorQuestion-c">
				<div class="editorQuestion_tab">
						<el-tabs v-model="editableTabsValue" type="card" editable @edit="handleTabsEdit">
							<el-tab-pane
							v-for="(item, index) in editableTabs"
							:key="index"
							:label="item.title"
							:name="item.name"
							>
								<ul>
									<li class="editorQuestion_ls clear">
										<span>题干</span>
										<div class="editorQuestion_lsr">
											<el-input type="textarea"
											:rows='5'
											resize='none'
											v-model="item.content.stem" placeholder="点击编辑单选题干，并选择正确答案"></el-input>
										</div>
									</li>
									<li class="editorQuestion_ls clear">
										<span>A</span>
										<div class="editorQuestion_lsr">
											<el-input v-model="item.content.choice1" placeholder="点击编辑选项"></el-input>
										</div>
									</li>
									<li class="editorQuestion_ls clear">
										<span>B</span>
										<div class="editorQuestion_lsr">
											<el-input v-model="item.content.choice2" placeholder="点击编辑选项"></el-input>
										</div>
									</li>
									<li class="editorQuestion_ls clear">
										<span>C</span>
										<div class="editorQuestion_lsr">
											<el-input v-model="item.content.choice3" placeholder="点击编辑选项"></el-input>
										</div>
									</li>
									<li class="editorQuestion_ls clear">
										<span>D</span>
										<div class="editorQuestion_lsr">
											<el-input v-model="item.content.choice4" placeholder="点击编辑选项"></el-input>
										</div>
									</li>
									<li class="editorQuestion_ls clear">
										<span>E</span>
										<div class="editorQuestion_lsr">
											<el-input v-model="item.content.choice5" placeholder="点击编辑选项"></el-input>
										</div>
									</li>
									<li class="editorQuestion_ls clear">
										<span>F</span>
										<div class="editorQuestion_lsr">
											<el-input v-model="item.content.choice6" placeholder="点击编辑选项"></el-input>
										</div>
									</li>
									<li class="editorQuestion_ls clear">
										<span>G</span>
										<div class="editorQuestion_lsr">
											<el-input v-model="item.content.choice7" placeholder="点击编辑选项"></el-input>
										</div>
									</li>
								</ul>
								<div class="editorQuestion_ls clear">
									<span>正确</span>
									<div class="editorQuestion_lsr">
										<!-- 多项 -->
										<template v-if="0">
											<el-checkbox-group v-model="item.checkList">
												<el-checkbox label="A"></el-checkbox>
												<el-checkbox label="B"></el-checkbox>
												<el-checkbox label="C"></el-checkbox>
												<el-checkbox label="D"></el-checkbox>
												<el-checkbox label="E"></el-checkbox>
												<el-checkbox label="F"></el-checkbox>
												<el-checkbox label="G"></el-checkbox>
											</el-checkbox-group>
										</template>
										<!-- 单项 -->
										<template>
											<el-radio-group v-model="item.radio">
												<el-radio :label="1">A</el-radio>
												<el-radio :label="2">B</el-radio>
												<el-radio :label="3">C</el-radio>
												<el-radio :label="4">D</el-radio>
											</el-radio-group>
										</template>
									</div>
								</div>
							</el-tab-pane>
						</el-tabs>
				</div>
				<div class="buttonCSS editorQuestion-btn">
					<el-button type="primary" plain @click="editorQuestion = false">取消</el-button>
					<el-button type="primary" @click="submitForm('ruleForm')">生成测试点</el-button>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	

	export default {
		props : ['compParam','activeIndex'],
		name: '',
		data() {
			return {
				thisIndex:'6',
				total_number:0,
				statusText: {
			      	success: '上传成功',  
			      	error: '上传出错',  
			     	uploading: '正在上传...',  
			      	paused: '暂停',  
			      	waiting: '等待上传'  
				},
				selectFileOrNot:false,  //是否选中文件
			    uploadOrNot:false, 		//是否已经上传
			    uploadInfo:{
					file_name:'',
					file_path:'',
					file_size:0
				},
				attrs: {
			      	//accept: ['application/vnd.openxmlformats-officedocument.wordprocessingml.document','application/msword']
			    },
		    	uploadOptions: {
			          target: this.BASE_URL+'/api/resource/res_upload',
			          testChunks: false,
			          headers:{Authorization : `Bearer `+this.$g.access_token},
			    },

	            ruleForm: {
	            	id:0,
	            	video_id:0,
					name: '',
					authority:'1',
					comment:'',
					select_or_not:'',
				},
	            listParam:{
					videoid:0,
					page_index:1,
					page_size:10,
				},
	
	      		selectFileShow:true,//是否显示选择文件按钮
				uploadRetryTimes:100,//文件最大重传次数
				selected: [],//表单checkbox
				listData: [],
				loading:{
					status:false,
					txt:'获取数据...',
				},
				addAttachments: false, //添加附件
				rules: {
					name: [
						{ required: true, message: '请输入附件名称', trigger: 'blur' },
						{ min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
					],
					select_or_not: [
		            	{ required: true,validator: this.validateName, message: '请选择文件'}
		            ],
				},
				//编辑题干
				editorQuestion: false,
				editableTabsValue: '2',
				editableTabs: [
					{
						title: '1',
						name: '1',
						content: {
							stem: '111', //题干
							choice1:'1',
							choice2:'',
							choice3:'',
							choice4:'',
							choice5:'',
							choice6:'',
							choice7:'',
						},
						checkList: ['A'],
						radio: 1
					}, {
						title: '2',
						name: '2',
						content: {
							stem: '222', //题干
							choice1:'2',
							choice2:'',
							choice3:'',
							choice4:'',
							choice5:'',
							choice6:'',
							choice7:'',
						},
						checkList: ['A','B'],
						radio: 2
					}
				],
				tabIndex: 2,
				 uploadLimitMax: 2000,

			}
		},
		computed: {

		},
		watch:{
			'activeIndex':{
	    		handler(n){
	    			if( n === this.thisIndex ){
	    				this.initFunc();
	    			}
	    		},
	    		
	    	},
		},
		mounted(){
		},
		methods: {
			initFunc(){
				this.getList();
				//this.$refs.videoPlayer.player.src({ type : "rtmp/mp4", src : this.compParam.play_url }) ;
				//this.getPointMark();
			},
			editFileBox( obj ){
				this.addAttachments = true;
				this.ruleForm.id = obj.id;
				this.ruleForm.name = obj.name;
				this.ruleForm.authority = obj.authority.toString();
				this.ruleForm.comment = obj.comment;
			},
			getList(){
		    	this.loading.status = true;
		    	this.listParam.videoid = this.compParam.id;
		    	// 重写成功回调
				let success = ( data => {
					this.loading.status = false;
					this.listData = data.data.data;
					this.total_number = data.data.data_sum;
				});
				let fail = ( data => {
					this.loading.status = false;
					this.$message.error(data.msg)
				})
  				this.$ajax.get('api/video/video_file_list',{params:this.listParam,func:{success:success,fail:fail}})
		    	
		    },
			saveFile(){
				let params = {};
					params.id = this.ruleForm.id;
					params.video_id = this.compParam.id;
					params.name =  this.ruleForm.name;
					params.authority =  this.ruleForm.authority;
					params.comment =  this.ruleForm.comment;
					if( parseInt( this.ruleForm.id ) === 0 ){
						params.path = this.uploadInfo.file_path;
						params.size = this.uploadInfo.file_size;
						params.postfix = this.uploadInfo.post_fix;
					}
					
				
            	let success = ( data=>{
            		this.addAttachments = false;
            		this.resetForm();
            		this.$message.success(data.msg);
            		this.getList();
            	})
            	//执行请求，并将回调方法变成config成员以便鉴权过期可以执行
            	if( !is_empty( params.id ) && parseInt( params.id ) > 0 ){
            		this.$ajax.put('api/video/video_file',params,{func:{success:success}})
            	}else{
					this.$ajax.post('api/video/video_file',params,{func:{success:success}})	
            	}
			},
			//上传成功的事件  
			fileSuccess (rootFile, file, message, chunk) { 
				this.$refs.uploader.uploader.cancel();
				var mess = JSON.parse(message);
					mess = handleResponseData(mess)
			 	if(parseInt( mess.data.status ) ===1 ){
			  		this.uploadOrNot = true;
			  		this.uploadInfo.file_name = mess.data.file_name;
			  		this.uploadInfo.file_path = mess.data.file_path;
			  		this.uploadInfo.post_fix = mess.data.post_fix;
			  		this.saveFile();
			  		this.getList()
			  }
			},
			fileFail( rootFile, file, message, chunk ){
				var mess = eval('(' + message + ')');
				if( parseInt( mess.error ) === 401 && this.uploadRetryTimes > 0){
					let callbcak = ( data=>{
						this.uploadRetryTimes--;
						this.$refs.uploader.uploader.retry( file );
	            	})
					this.get_access_token( callbcak );
				}else{
					this.$message.error(mess.msg);
				}
			},
			fileAdd( file,fileList ){
			

			},
			fileSubmit( files, fileList, event){

				if(fileList[0].size >  this.uploadLimitMax*1024*1024  && this.uploadLimitMax > 0){
					this.$message.warning('只允许上传'+this.uploadLimitMax+'M以内的文件');
						this.$refs.uploader.uploader.cancel();
				
				}else{
					this.ruleForm.select_or_not = '1';
					this.uploadInfo.file_size = fileList[0].size
					this.selectFileOrNot = true;
					this.selectFileShow = false;
				}

			},
			fileRemoved(file){
				this.ruleForm.select_or_not = '';
				this.selectFileOrNot = false;
				this.selectFileShow = true;
			},
			fileUpload(){
				this.$refs.uploader.uploader.resume();
			},
			handleSizeChange(val) {
		    	this.listParam.page_index = 1;
		    	this.listParam.page_size = val;
		    	this.getList()
		    },
		    handleCurrentChange(val) {
		    	this.listParam.page_index = val;
		    	this.getList();
		    },

			 //选中
		    tableSelectionChange(val) {
                this.selected = val;
            },
			//表单
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if( parseInt(this.ruleForm.id) > 0 ){
							this.saveFile();
						}else{
							this.fileUpload();
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			resetForm() {
				
				this.addAttachments = false;
				this.selectFileShow = true;
				this.ruleForm =  {
	            	id:0,
	            	video_id:0,
					name: '',
					authority:'1',
					comment:'',
					select_or_not:'',
				};
			},
			 delete(id){
		    	let success = ( data => {
		    		this.$message.success(data.msg)
		    		if(this.listData.length === id.length && this.listParam.page_index > 1){
		    			this.listParam.page_index--;
		    		}
					this.getList();
				});
		    	this.$ajax.delete('api/video/video_file',{params:{id:id},func:{success:success}})
		    },
		    delete_confirm(obj){
				let yes = ( data => {
					this.delete(obj.id);
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定将 '+obj.name+' 删除吗？'});

			},
			deleteMuilt_confirm(){
				if( this.selected.length === 0 ) {
					this.$message.warning("请选择要删除的项");
					return false;
				}
				let yes = ( data => {
					this.muilDelete();
				})
				let cancel = ( data => {})
				this.e_confirm({yes:yes,cancel:cancel,txt:'确定要删除选中的项吗？'});

			},
			muilDelete(){
				var ids = [];
				for (var i = this.selected.length - 1; i >= 0; i--) {
					ids.push(this.selected[i].id)
				}
				this.delete(ids);
			},
			down(path,name){
				//console.info(path,name);return false;
	    		var form = document.createElement("form");
			    form.action = this.BASE_URL+'/index/resource/download_video_file';
			    form.method = 'post';
			    form.style.display = "none";
				
	            var opt_path = document.createElement("textarea");
	            opt_path.name = 'path';
	            opt_path.value = path;
	            form.appendChild(opt_path);
	            var opt_name = document.createElement("textarea");
	            opt_name.name = 'name';
	            opt_name.value = name;
	            form.appendChild(opt_name);
			    document.body.appendChild(form);
			    form.submit();
			    document.body.removeChild(form);
	    	},

			//编辑题干
			handleTabsEdit(targetName, action) {
				if (action === 'add') {
					let newTabName = ++this.tabIndex + '';
					console.info(newTabName)
					this.editableTabs.push({
						title: newTabName,
						name: newTabName,
						content: this.editableTabs
					});
					this.editableTabsValue = newTabName;
				}
				if (action === 'remove') {
					let tabs = this.editableTabs;
					let activeName = this.editableTabsValue;
					if (activeName === targetName) {
						tabs.forEach((tab, index) => {
							if (tab.name === targetName) {
								let nextTab = tabs[index + 1] || tabs[index - 1];
								if (nextTab) {
									activeName = nextTab.name;
								}
							}
						});
					}

					this.editableTabsValue = activeName;
					this.editableTabs = tabs.filter(tab => tab.name !== targetName);
				}
			}

		}
	}
</script>